package com.tuanzi.loan.business.service.family.impl;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import com.tuanzi.loan.business.analyzer.BaiduYYSAnalyzer;
import com.tuanzi.loan.business.analyzer.PhoneContactAnalyzer;
import com.tuanzi.loan.business.repository.family.custom.UserInfoRepositoryCustom;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.retry.RetryException;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.tuanzi.loan.business.analyzer.BaiduJRAnalyzer;
import com.tuanzi.loan.business.analyzer.DianJinAnalyzer;
import com.tuanzi.loan.business.entity.family.*;
import com.tuanzi.loan.business.repository.family.*;
import com.tuanzi.loan.business.service.family.UserInfoService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.core.vo.PageSearcher;
import com.tuanzi.loan.vo.request.family.UserInfoSearchRequest;
import com.tuanzi.loan.vo.response.family.UserInfoSearchResponse;
import com.tuanzi.loan.vo.view.family.*;
import com.tuanzi.server.loan_base.util.PhoneNumNideUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @author Ray 2017/09/21
 */
@Debug
@Slf4j
@Service
@Transactional
@Retryable(value = { RetryException.class })
public class UserInfoServiceImpl implements UserInfoService {

	@Autowired
	private UserInfoRepository userInfoRepository;
	@Autowired
	private UserCreditRecordRepository userCreditRecordRepository;
	@Autowired
	private LoanOrderRepository loanOrderRepository;
	@Autowired
	private LoanApiRecordRepository loanApiRecordRepository;
	@Autowired
	private UserLabelRepository userLabelRepository;
	@Autowired
	private BaiduJRAnalyzer baiduJRAnalyzer;
	@Autowired
	private DianJinAnalyzer dianJinAnalyzer;
	@Autowired
	private BaiduYYSAnalyzer baiduYYSAnalyzer;
    @Autowired
    private UserInfoRepositoryCustom userInfoRepositoryCustom;
    @Autowired
    private PhoneContactAnalyzer phoneContactAnalyzer;

	@Override
	public Page<UserInfoSearchResponse> list(PageSearcher<UserInfoSearchRequest> pageSearcher) {
		return userInfoRepositoryCustom.list(pageSearcher.getSearchCondition(), pageSearcher.getPageable());
	}

	@Override
	public UserTagView loanUserTagView(Long userInfoId) {
		UserTagView view = new UserTagView();

		UserInfo userInfo = userInfoRepository.findOne(userInfoId);
		view.setUserId(userInfo.getUserId());
		view.setUserInfoView(structureUserInfoView(userInfo));
		view.setUserValidateView(structureUserValidateView(userInfo));
		view.setUserApiView(structureUserApiView(userInfo.getUserId()));
		view.setUserUnionView(structureUserUnionView(userInfo.getUserId()));
		view.setUserLabelView(structureUserLabelView(userInfo.getUserId()));

		return view;
	}
	
	@Override
	public UserTagView saveUserTagView(UserTagView userTagView) {
		UserLabel userLabel = userLabelRepository.findByUserId(userTagView.getUserId());
		if (userLabel == null) {
			userLabel = new UserLabel();
		}
		BeanUtils.copyProperties(userTagView.getUserLabelView(), userLabel);
		userLabel = userLabelRepository.save(userLabel);
		BeanUtils.copyProperties(userLabel, userTagView.getUserLabelView());
		return userTagView;
	}

	/**
	 * 构造用户标签库 - API订单记录VO
	 *
	 * @param userId
	 * @return UserApiView
	 */
	private UserApiView structureUserApiView(Long userId) {
		UserApiView view = new UserApiView();

		List<UserApiView.UserApiRecord> records = loanOrderRepository.findAllByUserId(userId).stream().sorted(Comparator.comparing(LoanOrder::getCtime).reversed()).map(x -> {

			UserApiView.UserApiRecord record = new UserApiView.UserApiRecord();
			BeanUtils.copyProperties(x, record);
			return record;

		}).collect(Collectors.toList());

		view.setRecords(records);
		return view;
	}

	/**
	 * 构造用户标签库 - 联登记录VO
	 *
	 * @param userId
	 * @return UserUnionView
	 */
	private UserUnionView structureUserUnionView(Long userId) {
		UserUnionView view = new UserUnionView();

		List<UserUnionView.UserUnionRecord> records = loanApiRecordRepository.findAllByUserId(userId).stream().sorted(Comparator.comparing(LoanApiRecord::getCtime).reversed())
				.map(x -> {

					UserUnionView.UserUnionRecord record = new UserUnionView.UserUnionRecord();
					BeanUtils.copyProperties(x, record);
					return record;

				}).collect(Collectors.toList());

		view.setRecords(records);
		return view;
	}

	/**
	 * 构造用户标签库 - 验证信息VO
	 * @return UserValidateView
	 */
	private UserValidateView structureUserValidateView(UserInfo userInfo) {
		UserValidateView view = new UserValidateView();
		UserValidateView.UserAuthInfo authInfo = new UserValidateView.UserAuthInfo();
        // 设置芝麻信息积分 暂为用户信息中的
        authInfo.setSesamePoint(userInfo.getSesamePoint());
        // 设置FaceId认证结果
        Boolean faceIdAuthResult = userInfoRepositoryCustom.getUserFaceAuthResult(userInfo.getUserId());
        if (faceIdAuthResult == null)
            authInfo.setFaceIdAuth("未认证");
        else
            authInfo.setFaceIdAuth(faceIdAuthResult ? "已通过" : "未通过");
        // 处理通讯录
        String phoneContactJsonStr = userInfoRepositoryCustom.getUserPhoneContactJson(userInfo.getUserId());
        authInfo.setPhoneContacts(phoneContactJsonStr == null ? "未授权" : "已授权");
        view.setContacts(phoneContactAnalyzer.getPhoneContact(phoneContactJsonStr ,true));
        // 处理百度、点金和运营商数据
		List<UserCreditRecord> userCreditRecords =
				userCreditRecordRepository.findAllByPhoneAndNameAndIdCard(userInfo.getMobnum(),userInfo.getPetname(),userInfo.getIdcard());
		for (UserCreditRecord userCreditRecord : userCreditRecords) {
			switch (userCreditRecord.getSourceType()) {
			case BAIDU_JR:
				view.setBaiduJR(baiduJRAnalyzer.analyse(userCreditRecord.getText1()));
				break;
			case DIAN_JIN:
				view.setDianJin(dianJinAnalyzer.analyze(userCreditRecord.getText1()));
				break;
			case BAIDU_YYS:
				view.setCallLogs(baiduYYSAnalyzer.getCallLogsAndIspRegTime(userCreditRecord.getText1(),authInfo));
				authInfo.setIspAuth(userCreditRecord.getText1()!= null || userCreditRecord.getText2() != null ? "已认证":"未认证");
				break;
			default:
				log.warn("Does not find any enum of {}", userCreditRecord.getSourceType());
				break;
			}
		}
		view.setAuthInfo(authInfo);
		return view;

	}

	/**
	 * 构造用户标签库 - 用户标签
	 *
	 * @param userId
	 * @return UserValidateView
	 */
	private UserLabelView structureUserLabelView(Long userId) {
		UserLabelView view = new UserLabelView();
		UserLabel userLabel = userLabelRepository.findByUserId(userId);
		if (userLabel != null) {
			BeanUtils.copyProperties(userLabel, view);
		}
		return view;

	}

	/**
	 * 构造用户标签库 - 用户信息VO
	 *
	 * @param userInfo
	 * @return UserInfoView
	 */
	private UserInfoView structureUserInfoView(UserInfo userInfo) {
		UserInfoView view = new UserInfoView();
		BeanUtils.copyProperties(userInfo, view);
		view.setFullAddress(concatStr(Lists.newArrayList(userInfo.getProvince(), userInfo.getCity(), userInfo.getIdenty(), userInfo.getAddress()), StringUtils.EMPTY));
		view.setSchoolTime(concatStr(Lists.newArrayList(userInfo.getComein(), userInfo.getComeout()), " / "));
		view.setFullCompanyAddress(concatStr(
				Lists.newArrayList(userInfo.getCompanyProvince(), userInfo.getCompanyCity(), userInfo.getCompanyDistrict(), userInfo.getCompanyAddress()), StringUtils.EMPTY));
		view.setFullBankAddress(concatStr(Lists.newArrayList(userInfo.getBankProvince(), userInfo.getBankCity(), userInfo.getBankDistrict()), StringUtils.EMPTY));
		return view;
	}

	private String concatStr(List<String> strs, String separator) {
		return strs.parallelStream().filter(StringUtils::isNotBlank).collect(Collectors.joining(separator));
	}

}
